package com.community.controller.visitor;

import com.community.entity.Result;
import com.community.entity.Visitor;
import com.community.entity.ContactRoom;
import com.community.service.visitor.VisitorService;
import com.community.service.room.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import static com.community.utils.JWT.getUserId;

@Controller
public class VisitorController {

    @Autowired
    private VisitorService visitorService;

    @Autowired
    private RoomService roomService;

    private static final Pattern MOBILE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    private static final Pattern DATE_PATTERN = Pattern.compile("^\\d{4}/\\d{2}/\\d{2}$");
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");


//1新增访客
    @ResponseBody
    @PostMapping("/visitor")
    public Result addVisitor(@RequestBody Visitor visitor, HttpServletRequest request) {

        if (!MOBILE_PATTERN.matcher(visitor.getMobile()).matches()) {
            return Result.fail(400, "手机号格式不正确");
        }

        if (!DATE_PATTERN.matcher(visitor.getVisitDate()).matches()) {
            return Result.fail(400, "访问日期格式错误，正确格式为 yyyy/MM/dd");
        }

        if (!isVisitDateValid(visitor.getVisitDate())) {
            return Result.fail(400, "访问日期必须在当前日期后三天内");
        }

        if (!isHouseApproved(visitor.getHouseId(), request)) {
            return Result.fail(400, "房屋ID不正确，无法邀请访客");
        }

        visitor.setStatus("1");
        String userId = getUserId(request);
        visitor.setUserId(userId);
        visitorService.addVisitor(visitor);
        return Result.success(visitor.getId());
    }

    //校验访问日期是否在三天内
    private boolean isVisitDateValid(String visitDateStr) {
        try {
            Date visitDate = DATE_FORMAT.parse(visitDateStr);

            //当前日期
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date currentDate = calendar.getTime(); // 当天 00:00:00

            long diffDays = (visitDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000);

            return diffDays >= 0 && diffDays <= 2;
        } catch (ParseException e) {
            return false;
        }
    }

    private boolean isHouseApproved(String houseId, HttpServletRequest request) {
        String userId = com.community.utils.JWT.getUserId(request);
        List<ContactRoom> approvedHouses = roomService.getStatusInfo(userId);
        return approvedHouses.stream().anyMatch(room -> room.getId().equals(houseId));
    }


//2访客记录
    @ResponseBody
    @GetMapping("/visitor")
    public Result getVisitorList(@RequestParam("current") String current,
                                 @RequestParam("pageSize")String  pageSize,
                                 HttpServletRequest request) {
        String userId = getUserId(request);
        Map<String, Object> data = visitorService.getVisitorsWithPagination(Integer.parseInt(current), Integer.parseInt(pageSize),userId);
        return Result.success(data);
    }



//3查询访客邀请详情
    @ResponseBody
    @GetMapping("/visitor/{id}")
    public Result getVisitorDetail(@PathVariable String id) {
        Map<String, Object> data = visitorService.getVisitorDetail(id);
        if (data == null) {
            return Result.fail(404, "访客邀请不存在");
        }
        return Result.success(data);
    }



//4查询访客邀请详情-分享页面
    @ResponseBody
    @GetMapping("/visitor/share/{encryptedData}")
    public Result getVisitorDetailByEncryptedData(@PathVariable String encryptedData) {
        Map<String, Object> data = visitorService.getVisitorDetailByEncryptedData(encryptedData);
        if (data == null) {
            return Result.fail(404, "访客邀请不存在或已失效");
        }
        return Result.success(data);
    }
}
